<template>
  <div>
    <quill-editor
      :content="editorHtml"
      :options="newOption"
      @change="editorChange"
      style="padding-top:30px;"
    >
    </quill-editor>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import { uploadImage } from '@/api/common_api'
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], //加粗，斜体，下划线，删除线
  ['blockquote', 'code-block'],
  [{ 'header': 1 }, { 'header': 2 }],
  [{ size: ["small", false, "large", "huge"] }], // 字体大小
  [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
  [{ 'direction': 'rtl' }],//文本方向
  [{ 'indent': '-1'}, { 'indent': '+1' }],//缩进
  [{ font: [] }],
  [{ align: [] }], //对齐方式
  ["image"],
  ["clean"] //清除字体样式
];
const handlers = {
  image: function image() {
    let self = this;
    var fileInput = this.container.querySelector("input.ql-image[type=file]");
    if (fileInput === null) {
      fileInput = document.createElement("input");
      fileInput.setAttribute("type", "file");
      fileInput.setAttribute(
        "accept",
        "image/png, image/gif, image/jpeg",
        "image/jpg"
      );
      fileInput.classList.add("ql-image");
      fileInput.addEventListener("change", async function() {
        let file = fileInput.files[0];
        if (!/image\/\w+/.test(file.type)) {
          this.$message.error('格式错误，请上传png、gif、jpg格式!')
          return false;
        }
        let form = new FormData();
        form.append("file", fileInput.files[0]);
        let req = await uploadImage(form);
        let length = self.quill.getSelection(true).index;
        self.quill.insertEmbed(length, "image", req.data);
        self.quill.setSelection(length + 1);
      });
      this.container.appendChild(fileInput);
    }
    fileInput.click();
  }
};
export default {
  name: 'CourseRichText',
  props: ['editorHtml', 'editorId'],
  components: { quillEditor },
  data () {
    return {
      newOption: {
        placeholder: '请填写内容',
        history: {
          delay: 100,
          maxStack: 100,
          userOnly: false
        },
        modules: {
          toolbar: {
            container:toolbarOptions,
            handlers: handlers
          },
        }
      }
    }
  },
  methods: {
    editorChange ({ editor, html, text }) {
      this.$emit('editorChange', html)
    }
  },
  /*watch: {
      //监控富文本内的变化
    text: function (val) {
      this.text = val
    }
  },*/
  mounted () {
  }
}
</script>

